package com.yk.system.task;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yk.system.entity.Device;
import com.yk.system.entity.Gateway;
import com.yk.system.service.DeviceService;
import com.yk.system.service.GatewayService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 设备状态定时任务
 *
 * @author lmx
 * @date 2024/3/5 14:23
 */
@Component
@RequiredArgsConstructor
public class DeviceStatusTask {

    private final DeviceService deviceService;
    private final GatewayService gatewayService;

    @Scheduled(cron = "0 */5 * * * ?")
    public void task() {
        List<Device> list = deviceService.list(Wrappers.lambdaQuery(Device.class).eq(Device::getStatus, 1));
        if (CollUtil.isEmpty(list)) {
            return;
        }
        list.forEach(device -> {
            if (Objects.isNull(device.getGatewayId())) {
                device.setStatus(Boolean.FALSE);
            }
            Gateway gateway = gatewayService.getById(device.getGatewayId());
            if (Objects.isNull(gateway) || !gateway.getStatus()) {
                device.setStatus(Boolean.FALSE);
            }
            if (!device.getStatus()) {
                deviceService.updateById(device);
            }
        });
    }
}
